package halberd.analysis;

import halberd.Analysiser;
import halberd.DataType;
import halberd.data.AnalysisResult;
import halberd.data.AvgResult;
import halberd.data.ImgData;

public class AvgAnalysiser implements Analysiser {

	public AnalysisResult analysis(ImgData input) {
		if (!canAnalysis(input)) {
			return null;
		}
		AvgResult avgResult = avg(input.getDatas(), input.getDataType(), input.getWidth(), input.getHeight());
		return avgResult;
	}

	private boolean canAnalysis(ImgData input) {
		if (input == null) {
			return false;
		}
		DataType dt = input.getDataType();
		if (dt == DataType.RGB) {
			return true;
		}
		if (dt == DataType.RGBA) {
			return true;
		}
		if (dt == DataType.GRAY) {
			return true;
		}
		return false;
	}

	private AvgResult avg(int[][][] src, DataType dataType, int w, int h) {
		AvgResult avgResult = new AvgResult();
		if (dataType.equals(DataType.GRAY)) {
			double gray=0;
			for (int i = 0; i < w; ++i) {
				for (int j = 0; j < h; ++j) {
					gray+=src[i][j][4];
				}
			}
			avgResult.setGray(gray/w/h);
		} else {
			double r=0,g=0,b=0;
			for (int i = 0; i < w; ++i) {
				for (int j = 0; j < h; ++j) {
					r+=src[i][j][0];
					g+=src[i][j][1];
					b+=src[i][j][2];
				}
			}
			avgResult.setRed(r/w/h);
			avgResult.setGreen(g/w/h);
			avgResult.setBlue(b/w/h);
		}

		return avgResult;
	}
}
